package com;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyAddTask extends RecursiveTask<Integer> {

    // 阈值
    private int threshold;
    private int start;
    private int end;

    public MyAddTask(int start, int end, int threshold) {
        this.start = start;
        this.end = end;
        this.threshold = threshold;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        // 如果粒度足够小，则直接计算
        if (end - start <= threshold) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 否则继续分割任务
            int middle = (start + end) / 2;
            MyAddTask left = new MyAddTask(start, middle, threshold);
            MyAddTask right = new MyAddTask(middle + 1, end, threshold);
            // 分割子任务
            ForkJoinTask<Integer> leftTask = left.fork();
            ForkJoinTask<Integer> rightTask = right.fork();
            // 执行子任务计算结果
            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();
            sum = leftResult + rightResult;
            System.out.println("子任务合并结果：sum=" + sum + " start=" + start + " end=" + end);
        }
        return sum;
    }
}
